package com.lkd.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.dao.TaskDetailsDao;
import com.lkd.emq.MqttProducer;
import com.lkd.emq.Topic;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.controller.BaseController;
import com.lkd.http.controller.TaskController;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private TaskController taskController;
    @Autowired
    private TaskDao taskDao;
    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private MqttProducer mqttProducer;
    @Autowired
    private TaskDetailsDao taskDetailsDao;




    private void noticeVMServiceStatus(TaskEntity taskEntity){
        // 封装协议
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());
        // 发送
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,taskCompleteContract);
        } catch (JsonProcessingException e) {
            throw new LogicException("工单完成发送错误");
        }

    }

    private void noticeVMServiceSupply(TaskEntity taskEntity){

        // 数据是订单详情task_details
        QueryWrapper<TaskDetailsEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskDetailsEntity::getChannelCode)
                .select(TaskDetailsEntity::getExpectCapacity)
                .select(TaskDetailsEntity::getSkuId)
                .select(TaskDetailsEntity::getSkuName)
                .select(TaskDetailsEntity::getSkuImage)
                .eq(TaskDetailsEntity::getTaskId,taskEntity.getTaskId());

    //    TaskDetailsEntity taskDetailsEntity = taskDetailsDao.selectOne(qw);
        List<TaskDetailsEntity> taskDetailsEntities = taskDetailsDao.selectList(qw);
        List<SupplyChannel> supplyDatas = new ArrayList<>();
        for (TaskDetailsEntity taskDetailsEntity : taskDetailsEntities) {

            for (SupplyChannel supplyData : supplyDatas) {
                BeanUtils.copyProperties(taskDetailsEntity,supplyData);
            }
        }
        //封装数据
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setSupplyData(supplyDatas);
        // 发送
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC,2,supplyContract);
        } catch (JsonProcessingException e) {
            throw new LogicException("补货发送错误");
        }


    }

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }

    @Override
    public Integer getLeastTask(Long regionId, Boolean isRepair) {
        String roleCode ="1002";
        if(isRepair){
            roleCode="1003";
        }
        String key= VMSystem.REGION_TASK_KEY_PREF+LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+regionId+"."+roleCode;
        Set<Object> set = redisTemplate.opsForZSet().range(key, 0, 0);
        if (set==null||set.isEmpty()){
            return 0;
        }
        return (Integer) set.stream().collect(Collectors.toList()).get(0);// get(索引) 获得的是redis中的value, 不包括Key
    }


    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId,VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }

    private boolean hasTask(String innerCode,int productionType){
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode,innerCode)
                .eq(TaskEntity::getProductTypeId,productionType)
                .le(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS);
        return this.count(qw) > 0;
    }
    @Transactional
    @Override
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if(vm==null){
            throw new LogicException("该机器不存在");
        }
        //跨服务查询用户微服务，得到用户名
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if(user==null){
            throw new LogicException("该用户不存在");
        }

        //  TODO: 校验售货机的状态与工单类型是否相符
        if(vm.getStatus()==VMSystem.VM_STATUS_RUNNING){
            if(taskViewModel.getProductType()==VMSystem.TASK_STATUS_CREATE){
                throw new LogicException("设备和工单状态不匹配");
            }
        }else{
        if(taskViewModel.getProductType()==VMSystem.TASK_STATUS_PROGRESS||taskViewModel.getProductType()==VMSystem.TASK_STATUS_FINISH){
            throw new LogicException("设备和工单状态不匹配");
        }}

        //TODO: 我们在创建工单时应该校验这台设备是否有未完成的同类型工单，如果存在则不能创建。
        // 查询创建工单的设备是否存在工单
   /*     List<TaskEntity> list = taskDao.selectbyInnerCode(taskViewModel.getInnerCode());
       if(list.size()!=0){
           // 是否存在同类型，状态是否未完成
           list.stream().forEach(e->{
               if(taskViewModel.getProductType()==e.getProductTypeId()&&(e.getTaskStatus()==VMSystem.TASK_STATUS_CREATE||e.getTaskStatus()==VMSystem.TASK_STATUS_PROGRESS)){
               throw new LogicException("存在未完成的同类型工单");
           }});

       }*/
        if(hasTask(taskViewModel.getInnerCode(),taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }

        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());//工单编号
        BeanUtils.copyProperties(taskViewModel,taskEntity);//复制属性
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);//工单状态
        taskEntity.setProductTypeId(taskViewModel.getProductType());//工单类型

        taskEntity.setAddr(vm.getNodeAddr());//地址
        taskEntity.setRegionId(  vm.getRegionId() );//区域
        taskEntity.setUserName(user.getUserName());//用户名
        this.save(taskEntity);
        //如果是补货工单，向 工单明细表插入记录
        if(taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            taskViewModel.getDetails().forEach(d->{
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties( d,detailsEntity );
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }
// TODO:redis中存入工单维修人员的工单数+1
        updateTaskZSet(taskEntity,1);

        return true;
    }

    private void updateTaskZSet(TaskEntity taskEntity, int score) {
String roleCode="1003";//运维人员
        if(taskEntity.getProductTypeId().intValue()==2){
            roleCode="1002";
        }
        String key= VMSystem.REGION_TASK_KEY_PREF+LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+taskEntity.getRegionId() +"."+roleCode;
        redisTemplate.opsForZSet().incrementScore(key,taskEntity.getUserId(),score);
    }


    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode(){
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key= "lkd.task.code."+date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            redisTemplate.opsForValue().set(key,1L, Duration.ofDays(1) );
            return date+"0001";
        }
        return date+  Strings.padStart( redisTemplate.opsForValue().increment(key,1).toString(),4,'0');
    }


    @Override
    public boolean accept(Long id) {
        TaskEntity task = this.getById(id);  //查询工单

        //TODO: 判断当前工单是否是待处理状态，如果不是则抛出异常。
        if(task.getTaskId()!=1){
            throw new LogicException("当前工单不是待处理状态");
        }
        //TODO: 判断当前工单的执行人是否为当前登录用户
        if(task.getUserId()!=taskController.getUserId()){
            throw new LogicException("当前工单执行人不是当前登录用户");
        }


        task.setTaskStatus( VMSystem.TASK_STATUS_PROGRESS );//修改工单状态为进行
        return this.updateById(task);
    }

    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        TaskEntity task = this.getById(id);  //查询工单

        //TODO: 判断当前工单是否是未结束状态，如果是已完成或已取消则抛出异常。
        if(task.getTaskStatus()==VMSystem.TASK_STATUS_PROGRESS||task.getTaskStatus()==VMSystem.TASK_STATUS_FINISH){
            throw new LogicException("当前工单未结束或已完成");
        }
        //TODO: 判断当前工单的执行人或创建人是否为当前登录用户
        if(task.getUserId()!=taskController.getUserId()&&task.getAssignorId()!=taskController.getUserId()){
            throw new LogicException("当前工单执行人或创建人不是当前登录用户");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_CANCEL  );
        task.setDesc(cancelVM.getDesc());
        updateTaskZSet(task,-1);
        return this.updateById(task);
    }

    @Override
    public boolean completeTask(long id) {

        TaskEntity taskEntity = this.getById(id);
        //TODO: 判断当前工单是否是未结束状态，如果是已完成或已取消则抛出异常。
        if(taskEntity.getTaskStatus()==VMSystem.TASK_STATUS_PROGRESS||taskEntity.getTaskStatus()==VMSystem.TASK_STATUS_FINISH){
            throw new LogicException("当前工单未结束或已完成");
        }
        //TODO: 判断当前工单的执行人或创建人是否为当前登录用户
        if(taskEntity.getUserId()!=taskController.getUserId()&&taskEntity.getAssignorId()!=taskController.getUserId()){
            throw new LogicException("当前工单执行人或创建人不是当前登录用户");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态
        this.updateById(taskEntity);

        // 投放或撤机
        if(taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_DEPLOY||
                taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_REVOKE){
            noticeVMServiceStatus(taskEntity);
        }
        if(taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_SUPPLY){
            noticeVMServiceSupply(taskEntity);
        }

        return true;
    }

}
